/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.cmd;

import com.google.common.base.Strings;
import com.je.bpm.core.model.BpmnModel;
import com.je.bpm.core.model.FlowElement;
import com.je.bpm.core.model.config.task.TaskPassRoundConfigImpl;
import com.je.bpm.core.model.task.KaiteBaseUserTask;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.delegate.DelegateHelper;
import com.je.bpm.engine.impl.identity.Authentication;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.*;
import com.je.bpm.engine.upcoming.UpcomingCommentInfoDTO;
import com.je.bpm.runtime.shared.RemoteCallServeManager;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 传阅命令
 */
public class PassRoundTaskCmd implements Command<Void>, Serializable {

    private static final String CONTENT_FORMAT = "%s传阅任务给您，请您阅览！";

    private static final long serialVersionUID = 1L;
    private String taskId;
    private List<String> users;
    private String prod;
    private String beanId;
    private String tableCode;
    private String from;

    public PassRoundTaskCmd(String taskId) {
        this.taskId = taskId;
    }

    public PassRoundTaskCmd(String taskId, List<String> users, String prod, String beanId, String tableCode) {
        this.taskId = taskId;
        this.users = users;
        this.prod = prod;
        this.beanId = beanId;
        this.tableCode = tableCode;
        this.from = Authentication.getAuthenticatedUser().getDeptId();
    }


    public PassRoundTaskCmd(String taskId, List<String> users, String prod, String beanId, String tableCode, String from) {
        this.taskId = taskId;
        this.users = users;
        this.prod = prod;
        this.beanId = beanId;
        this.tableCode = tableCode;
        this.from = from;
        if (Strings.isNullOrEmpty(from)) {
            this.from = Authentication.getAuthenticatedUser().getDeptId();
        }
    }

    @Override
    public Void execute(CommandContext commandContext) {
        if (StringUtils.isEmpty(taskId)) {
            throw new ActivitiException("The task id can't be null in pass round!");
        }

        TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();
        TaskEntity task = taskEntityManager.findById(taskId);

        if (task == null) {
            throw new ActivitiException("Can not find the task with the task id!");
        }

        if (users != null && users.size() > 0) {
            passRoundWithUsers(commandContext, task);
            return null;
        }

        BpmnModel bpmnModel = commandContext.getProcessEngineConfiguration().getRepositoryService().getBpmnModel(task.getProcessDefinitionId());
        FlowElement taskFlowElement = bpmnModel.getFlowElement(task.getTaskDefinitionKey());
        KaiteBaseUserTask kaiteBaseUserTask = (KaiteBaseUserTask) taskFlowElement;
        if (kaiteBaseUserTask.getTaskPassRoundConfig().isAuto()) {
            TaskPassRoundConfigImpl taskPassRoundConfig = kaiteBaseUserTask.getTaskPassRoundConfig();
            passRoundWithConfig(commandContext, task, taskPassRoundConfig);
        }
        return null;
    }

    /**
     * 从传阅配置中传阅
     *
     * @param commandContext
     * @param task
     */
    private void passRoundWithConfig(CommandContext commandContext, TaskEntity task, TaskPassRoundConfigImpl taskPassRoundConfig) {
        if (!taskPassRoundConfig.isEnable()) {
            throw new ActivitiException("Can't pass round the task because it is disabled.");
        }
        RemoteCallServeManager remoteCallServeManager = commandContext.getProcessEngineConfiguration().getRemoteCallServeManager();
        Map<String, Object> bean = (Map<String, Object>) remoteCallServeManager.doGet(prod, beanId, tableCode, null);
        Object o = commandContext.getProcessEngineConfiguration().getTaskService().getCirculatedAssignment(taskId, prod, bean);
        if (o instanceof List) {
            users = commandContext.getProcessEngineConfiguration().getResultUserParser().
                    parserCirculationResultUserToListString(o);
            //如果启动人传阅
            passRoundWithUsers(commandContext, task);
        }
    }

    private void passRoundWithUsers(CommandContext commandContext, TaskEntity task) {
        PassRoundEntityManager passRoundEntityManager = commandContext.getProcessEngineConfiguration().getPassRoundEntityManager();
        PassRoundEntity passRoundEntity;
        //去重
        List<String> isToUsers = new ArrayList<>();
        for (String eachUser : users) {
            if (from.equals(eachUser)) {
                continue;
            }
            if (isToUsers.contains(eachUser)) {
                continue;
            }
            isToUsers.add(eachUser);
            passRoundEntity = new PassRoundEntityImpl();
            passRoundEntity.setCreateTime(commandContext.getProcessEngineConfiguration().getClock().getCurrentTime());
            passRoundEntity.setFrom(from);
            passRoundEntity.setTo(eachUser);
            passRoundEntity.setTaskId(taskId);
            passRoundEntity.setTaskName(task.getName());
            passRoundEntity.setProcessDefinitionId(task.getProcessDefinitionId());
            passRoundEntity.setProcessInstanceId(task.getProcessInstanceId());
            passRoundEntityManager.insert(passRoundEntity);
        }
        Map<String, String> params = new HashMap<>();
        params.put("userIds", String.join(",", isToUsers));
        UpcomingCommentInfoDTO upcomingInfo = DelegateHelper.buildUpcomingInfo(null,
                String.format(CONTENT_FORMAT, Authentication.getAuthenticatedUser().getName()),
                SubmitTypeEnum.PASSROUND, task.getBusinessKey(), taskId, params);
        commandContext.getProcessEngineConfiguration().getActivitiUpcomingRun().completeUpcoming(upcomingInfo);
    }

}

